package gops

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

// GinValidateToken 中间件：验证请求头token
func GinValidateToken(expectedToken string) gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenAuthorization := c.GetHeader("Authorization")
		tokenToken := c.GetHeader("Token")
		if tokenAuthorization != expectedToken && tokenToken != expectedToken {
			c.JSON(http.StatusForbidden, gin.H{
				"code":    http.StatusForbidden,
				"message": "请求的token无效",
				"data":    nil,
			})
			c.Abort()
			return
		}
		c.Next()
	}
}

type ginResponse struct {
	Code int         `json:"code"`
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}

func ginResult(code int, data interface{}, msg string, c *gin.Context) {
	// 开始时间
	c.JSON(http.StatusOK, ginResponse{
		code,
		data,
		msg,
	})
}

func GinOk(c *gin.Context) {
	ginResult(0, map[string]interface{}{}, "操作成功", c)
}

func GinOkWithMessage(message string, c *gin.Context) {
	ginResult(0, map[string]interface{}{}, message, c)
}

func GinOkWithData(data interface{}, c *gin.Context) {
	ginResult(0, data, "成功", c)
}

func GinOkWithDetailed(data interface{}, message string, c *gin.Context) {
	ginResult(0, data, message, c)
}

func GinFail(c *gin.Context) {
	ginResult(-1, map[string]interface{}{}, "操作失败", c)
}

func GinFailWithMessage(message string, c *gin.Context) {
	ginResult(-1, map[string]interface{}{}, message, c)
}

func GinFailWithDetailed(data interface{}, message string, c *gin.Context) {
	ginResult(-1, data, message, c)
}
